package com.qf.business.user.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qf.business.user.mapper.UserMapper;
import com.qf.business.user.service.ScoreDetailsService;
import com.qf.business.user.service.UserService;
import com.qf.commons.redis.cache.annotation.CacheGet;
import com.qf.data.user.entity.ScoreDetails;
import com.qf.data.user.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;

/**
 * (User)表服务实现类
 *
 * @author makejava
 * @since 2022-07-04 11:10:55
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private ScoreDetailsService scoreDetailsService;

    /**
     * 根据openid 查询微信的用户信息
     * @param openId
     * @return
     */
    @Override
    public User queryByOpenId(String openId) {
        User user = super.query()
                .eq("open_id", openId)
                .one();
        return user;
    }

    /**
     * 根据用户id 查询用户积分值
     * @param uid
     * @return
     */
    @Override
    public Integer queryScore(Long uid) {
        User user = super.query().select("score").eq("id", uid)
                .one();
        return user.getScore();
    }

    /**
     * 修改指定用户的积分
     * @param uid - 用户id
     * @param score - 操作的积分值
     * @param type - 操作类型 0 - 添加 1 - 扣减
     * @return
     */
    @Override
    @Transactional
    public long updateScoreByUid(Long uid, Integer score, Integer type, Integer actionType) {
        //修改积分
        int result = userMapper.updateScoreByUid(uid, score, type);
        if (result > 0) {
            //调用积分流水的业务
            ScoreDetails scoreDetails = new ScoreDetails();
            scoreDetails.setUid(uid);
            scoreDetails.setType(actionType);//操作类型
            scoreDetails.setScore(score);//操作积分
            scoreDetailsService.save(scoreDetails);
            return scoreDetails.getId();
        }
        return result;
    }

    /**
     * 根据id查询用户信息 ， 通过多级缓存实现
     * @param id
     * @return
     */
    @CacheGet("'cache_user_' + #id")
    @Override
    public User getById(Serializable id) {
        return super.getById(id);
    }
}


